package com.example.hospital.dispensarypurchasesandsells.controller;

import com.example.hospital.dispensarypurchasesandsells.pojo.Inventory;
import com.example.hospital.dispensarypurchasesandsells.pojo.RecordInfo;
import com.example.hospital.dispensarypurchasesandsells.repository.InventoryRepository;
import com.example.hospital.dispensarypurchasesandsells.repository.MedicineRepo;
import com.example.hospital.dispensarypurchasesandsells.service.Impl.InventoryServiceImpl;
import com.example.hospital.dispensarypurchasesandsells.service.Impl.MedicineServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class InventoryController {

    @Autowired
    private InventoryServiceImpl inventoryService;

    @Autowired
    private MedicineServiceImpl medicineService;

    @GetMapping("/inventory")
    public String inventory(Model model){

        List<RecordInfo> recordInformations=inventoryService.findRecordInfoList();  //查询所有库存记录并放入请求域中
        model.addAttribute("recordInformations",recordInformations);
        return "inventory";
    }

    @PostMapping("addMedicine")
    public String addMedicine(RecordInfo recordInfo){
        recordInfo.getMedicine().setMedicineId(medicineService.findMaxId()+1);
        recordInfo.getInventory().setMedicineId(recordInfo.getMedicine().getMedicineId());
        medicineService.save(recordInfo.getMedicine());
        inventoryService.save(recordInfo.getInventory());
        return "redirect:/inventory";
    }

    @PostMapping("/deleteMedicine")
    public String deleteMedicine(HttpServletRequest request){
        int medicineId = Integer.parseInt(request.getParameter("medicine_id"));

       inventoryService.delete(medicineId);
        medicineService.delete(medicineId);

        return "redirect:/inventory";
    }

    @PostMapping("/editInventory")
    public String  editInventory(HttpServletRequest request){
        int medicineId = Integer.parseInt(request.getParameter("medicine_id"));
        int inventory = Integer.parseInt(request.getParameter("inventory"));

        Inventory inventory1=new Inventory();
        inventory1.setMedicineId(medicineId);
        inventory1.setInventory(inventory);

        inventoryService.save(inventory1);

        return "redirect:/inventory";
    }


}
